// utils/request.js

// 配置基础URL
const BASE_URL = 'https://pcapi-xiaotuxian-front.itheima.net'

// 添加请求拦截器
uni.addInterceptor('request', {
	// 请求前拦截
	invoke(args) {
		// 拼接完整URL
		args.url = BASE_URL + args.url
		// 添加请求头（如Token）
		args.header = {
			...args.header,
			'Authorization': "Bearer "+uni.getStorageSync('token') || '',
			'Content-Type': 'application/json',
			"source-client":"miniapp"
		}

	},

	success(args) {
		if(args.data.code!=1){
			uni.showToast({
				title:	args.data.msg||'请求失败',
				icon:"none"
			})
		}
		return args.data
	},
	// 请求失败拦截
	fail(err) {
		uni.hideLoading()
		uni.showToast({
			title: '网络错误，请稍后重试',
			icon: 'none'
		})
		return Promise.reject(err)
	}
})

// 封装uni.request为Promise
export const request = (options) => {
	return new Promise((resolve, reject) => {
		uni.request({
			...options,
			success: (res) => resolve(res.data),
			fail: (err) => reject(err)
		})
	})
}

// 封装常用方法
export const get = (url, data, options = {}) => {
	return request({
		url,
		data,
		method: 'GET',
		...options
	})
}

export const post = (url, data, options = {}) => {
	return request({
		url,
		data,
		method: 'POST',
		...options
	})
}
// 封装常用方法
export const del = (url, data, options = {}) => {
	return request({
		url,
		data,
		method: 'DELETE',
		...options
	})
}

export const put = (url, data, options = {}) => {
	return request({
		url,
		data,
		method: 'PUT',
		...options
	})
}
